<?php defined('IN_KG') or exit('Access Invalid!'); ?>



<style>
    .selected-group-goods {
        background-color: #FFF;
        width: 100%;
        padding: 9px;
        margin-bottom: 10px;
        border: solid 1px #E6E6E6;
        box-shadow: 2px 2px 0 rgba(153,153,153,0.1);
    }
</style>
<div class="tabmenu">
    <?php include template('layout/submenu'); ?>
</div>
<div class="ncsc-form-default">
    <form id="add_form" action="index.php?control=store_groupbuy&op=groupbuy_save" method="post"
          enctype="multipart/form-data">
        <dl>
            <dt><i class="required">*</i><?php echo $lang['group_name'] . $lang['nc_colon']; ?></dt>
            <dd>
                <input class="w400 text" name="groupbuy_name" type="text" id="groupbuy_name" value="" maxlength="30"/>
                <span></span>
                <p class="hint"><?php echo $lang['group_name_tip']; ?></p>
            </dd>
        </dl>
        <dl>
            <dt>抢购副标题<?php echo $lang['nc_colon']; ?></dt>
            <dd>
                <input class="w400 text" name="groupbuy_remark" type="text" id="remark" value="" maxlength="30"/>
                <span></span>
                <p class="hint">抢购活动副标题最多可输入30个字符</p>
            </dd>
        </dl>
        <dl>
            <dt><i class="required">*</i><?php echo $lang['start_time']; ?><?php echo $lang['nc_colon']; ?></dt>
            <dd>
                <input id="start_time" name="start_time" type="text" class="text w130"/><em class="add-on"><i
                            class="icon-calendar"></i></em><span></span>
                <p class="hint"><?php echo '抢购开始时间不能小于' . date('Y-m-d H:i', $output['groupbuy_start_time']); ?></p>
            </dd>
        </dl>
        <dl>
            <dt><i class="required">*</i><?php echo $lang['end_time']; ?><?php echo $lang['nc_colon']; ?></dt>
            <dd>
                <input id="end_time" name="end_time" type="text" class="text w130"/><em class="add-on">
                    <i class="icon-calendar"></i></em><span></span>
                <p class="hint">
                    <?php if (!$output['isOwnShop']) { ?>
                    <?php echo '抢购开始时间不能大于' . date('Y-m-d H:i', $output['current_groupbuy_quota']['end_time']); ?>
                </p>
                <?php } ?>

            </dd>
        </dl>
        <dl>
            <dt><i class="required">*</i><?php echo $lang['groupbuy_goods'] . $lang['nc_colon']; ?></dt>
            <dd>

                <div nctype="groupbuy_goods_info" class="selected-group-goods " style="display:none;" id="contentList">
                    <div data-id="tpl">
                        <div >
                            <template v-text="goods">
                                <p v-for="item in goods" data-id="group_tpl">
                                    <span style="max-width: 200px;overflow: hidden">{{item.goods_spec}}-{{item.goods_id}}</span>
                                    <span data-id="old_price">原价: {{item.source_price}}</span>  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    <span>团购价:</span><input type="text" id="" class="text str" :value="item.goods_price" :name="'goods['+item.goods_id+']'">
                                    <!--<input type="text" class="w70 text" style="vertical-align: middle;" name="{{item.goods_price}}" data-price="{{item.goods_price}}" value="{{item.goods_price}}">-->
                                </p>
                            </template>
                        </div>
                        <div class="goods-price" style="text-align: center;height: 50px;margin-top: 20px;">
                            <label>参团人数<input class="w70 text" data-id="upper_count" name="groupbuy_persons" type="group_num"/></label>
                            <input type="text" data-id="txt_count" value="1" class="text" style="text-align: center">
                            <!--v-on:keyup="alter_price($event)"-->
                        </div>
                    </div>
                </div>


                <a href="javascript:void(0);" id="btn_show_search_goods" class="ncbtn ncbtn-aqua">选择商品</a>
                <a href="javascript:void(0);" id="btn_show_copy_goods" class="ncbtn ncbtn-aqua">复制商品</a>
                <input id="groupbuy_goods_id" name="groupbuy_goods_id" type="hidden" value=""/>
                <span></span>
                <div id="div_search_goods" class="div-goods-select mt10" style="display: none;">
                    <table class="search-form">
                        <tr>
                            <th class="w150">
                                <strong>第一步：搜索店内商品</strong>
                            </th>
                            <td class="w160">
                                <input id="search_goods_name" type="text w150" class="text" name="goods_name" value=""/>
                            </td>
                            <td class="w70 tc">
                                <a href="javascript:void(0);" id="btn_search_goods" class="ncbtn"/><i
                                        class="icon-search"></i><?php echo $lang['nc_search']; ?></a></td>
                            <td class="w10"></td>
                            <td>
                                <p class="hint">不输入名称直接搜索将显示店内所有普通商品，特殊商品不能参加。</p>
                            </td>
                        </tr>
                    </table>
                    <div id="div_goods_search_result" class="search-result" style="width:739px;"></div>
                    <a id="btn_hide_search_goods" class="close" href="javascript:void(0);">X</a>
                </div>
                <p class="hint"><?php echo $lang['groupbuy_goods_explain']; ?>
                    <!--</br><span class="red">抢购生效后该商品的所有规格SKU都将执行统一的抢购价格</span>-->
                </p>
            </dd>
        </dl>

       <!-- <dl>
            <dt><i class="required">*</i><?php /*echo $lang['groupbuy_price'] . $lang['nc_colon']; */?></dt>
            <dd>
                <input class="w70 text" id="groupbuy_price" name="groupbuy_price" type="text" value=""/><em
                        class="add-on"><i class="icon-renminbi"></i></em> <span></span>
                <p class="hint"><?php /*echo $lang['groupbuy_price_tip']; */?></p>
            </dd>
        </dl>-->

       <!-- <dl>
            <dt>参团人数</dt>
            <dd>
                <input class="w70 text" id="upper_count" name="groupbuy_persons" type="group_num" value="10"/>
                <span></span>
                <p class="hint">参团人数</p>
            </dd>
        </dl>-->
        <dl>
            <dt>团购总数</dt>
            <dd>
                <input class="w70 text" id="upper_limit" name="upper_limit" type="group_num" value="0"/>
                <span></span>
                <p class="hint">团购总数满足后将结束活动</p>
            </dd>
        </dl>

        <dl>
            <dt>预付定金</dt>
            <dd>
                <input class="w70 text" id="groupbuy_deposit" name="groupbuy_deposit" type="group_num" value="0"/>
                <span></span>
                <p class="hint">团购总数满足后将结束活动</p>
            </dd>
        </dl>


        <dl>
            <dt><?php echo $lang['group_intro'] . $lang['nc_colon']; ?></dt>
            <dd>
                <?php showEditor('groupbuy_intro', '', '740px', '360px', '', 'false', false); ?>
                <!--<p class="hr8">
                    <a class="des_demo ncbtn" href="index.php?control=store_album&op=pic_list&item=groupbuy">
                        <i class="icon-picture"></i>
                        <?php /*echo $lang['store_goods_album_insert_users_photo']; */?>
                    </a>
                </p>
                <p id="des_demo" style="display:none;"></p>-->
            </dd>
        </dl>

        <dl>
            <dt>是否推荐：</dt>
            <dd>
                <ul class="ncsc-form-radio-list">
                    <li><label for="bundling_status_1">
                            <input type="radio" name="recommended" value="1" id="bundling_status_1">
                            是</label></li>
                    <li><label for="bundling_status_0">
                            <input type="radio" name="recommended" value="0" id="bundling_status_0" checked="checked">
                            否</label></li>
                </ul>
            </dd>
        </dl>


        <div class="bottom"><label class="submit-border">
                <input type="submit" class="submit" value="<?php echo $lang['nc_submit']; ?>"></label>
        </div>

    </form>
</div>
<script src="https://unpkg.com/vue"></script>
<script>
    var Item = new Vue({
        el:'#contentList',
        data:{
            goods:[]
        },
        methods:{
            alter_price:function (e) {
                var num = $("input[data-id='txt_count']").val();
                console.log(num);
                console.log($(this));

                var float_rule = /^0\.[1-9]/;
                var minus_rule = /^-\d+$/;
                if (float_rule.test(num)){
                    var price_g = $(this).parent().prev().find("input");
                    for(var key in this.goods){
                        for(var m=0; m<price_g.length;m++){
                            price_g[m].val() = parseInt(this.goods[key].source_price * num);
//                            this.goods[key].goods_price = parseInt(this.goods[key].source_price * num);
                        }
                    }

                }else if(minus_rule.test(num)){
                    for(var key in this.goods){
                        this.goods[key].goods_price = this.goods[key].source_price - Math.abs(num);
                    }
                }


            }
        }
    })
</script>




<link rel="stylesheet" type="text/css"
      href="<?php echo RESOURCE_SITE_URL; ?>/js/jquery-ui/themes/ui-lightness/jquery.ui.css"/>
<link rel="stylesheet" type="text/css"
      href="<?php echo RESOURCE_SITE_URL; ?>/js/jquery-ui-timepicker-addon/jquery-ui-timepicker-addon.min.css"/>
<script src="<?php echo RESOURCE_SITE_URL; ?>/js/jquery.ajaxContent.pack.js"></script>
<script src="<?php echo RESOURCE_SITE_URL; ?>/js/jquery-ui/i18n/zh-CN.js"></script>
<script src="<?php echo RESOURCE_SITE_URL; ?>/js/jquery-ui-timepicker-addon/jquery-ui-timepicker-addon.min.js"></script>
<script type="text/javascript" src="<?php echo RESOURCE_SITE_URL; ?>/js/fileupload/jquery.iframe-transport.js"
        charset="utf-8"></script>
<script type="text/javascript" src="<?php echo RESOURCE_SITE_URL; ?>/js/fileupload/jquery.ui.widget.js"
        charset="utf-8"></script>
<script type="text/javascript" src="<?php echo RESOURCE_SITE_URL; ?>/js/fileupload/jquery.fileupload.js"
        charset="utf-8"></script>
<script type="text/javascript">
    $(document).ready(function () {
//        商品name属性改写
        $("input[data-id='upper_count']").change(function(){
//             var str_g = $('p[data-id="group_tpl"] input')
             var str_g = $(this).parent().parent().prev().find("input");
//             console.log(str_g);
             var flg ='[' + $(this).val() + ']';
//             商品
             for(i=0;i<str_g.length;i++){
                var str = str_g[i].name;
                var index1 = str.lastIndexOf("[");
                var index2 = str.lastIndexOf("]");
//                console.log($(this).val());
                var f_str = str.substring(0,5);
                var a_str = str.substring(index1,index2+1);
                var new_str = f_str.concat(flg,a_str);
                str_g[i].name = new_str;
             }
//             人数
console.log($(this))
            var persons_str = $(this)[0].name;
//            console.log("renshu" + persons_str)
            var f_persons_str = persons_str.substring(0,16);
            var new_persons_str = f_persons_str.concat(flg);
            $(this)[0].name = new_persons_str;
//            折扣
        })


//       商品复制按钮
        $('#btn_show_copy_goods').on('click', function () {
             $("#contentList").append($('[data-id="tpl"]:first').clone(true));
         });
//         价格计算
        $("input[data-id='txt_count']").change(function(){
            var num = $(this).val();
//            console.log(num);
//            console.log($(this));

            var float_rule = /^0\.[1-9]/;
            var minus_rule = /^-\d+$/;
            if (float_rule.test(num)){
                var price_g = $(this).parent().prev().find("[data-id='old_price']");
                var new_price_g = $(this).parent().prev().find("input");
//                    console.log(price_g);
                    for(var m=0; m<price_g.length;m++){
//                        console.log(price_g[m])
                        var s_old_price = price_g[m].textContent.substr(4);
//                        console.log(s_old_price);
                        var n_old_price = Number(s_old_price);
//                        console.log("jiage"+(n_old_price * num))
                        new_price_g[m].value = parseInt(n_old_price * num);
                    }
            }else if(minus_rule.test(num)){
                var price_g = $(this).parent().prev().find("[data-id='old_price']");
                var new_price_g = $(this).parent().prev().find("input");
//                    console.log(price_g);
                    for(var m=0; m<price_g.length;m++){
//                        console.log(price_g[m])
                        var s_old_price = price_g[m].textContent.substr(4);
//                        console.log(s_old_price);
                        var n_old_price = Number(s_old_price);
//                        console.log("jiage"+(n_old_price * num))
                        new_price_g[m].value = parseInt(n_old_price - Math.abs(num));
                    }
            }

        })

        $('#start_time').datetimepicker({
            controlType: 'select'
        });

        $('#end_time').datetimepicker({
            controlType: 'select'
        });

        $('#btn_show_search_goods').on('click', function () {
            $('#div_search_goods').show();
        });

        $('#btn_hide_search_goods').on('click', function () {
            $('#div_search_goods').hide();
        });

        //搜索商品
        $('#btn_search_goods').on('click', function () {
            var url = "<?php echo urlShop('store_groupbuy', 'search_goods');?>";
            url += '&' + $.param({goods_name: $('#search_goods_name').val()});
            $('#div_goods_search_result').load(url);
        });

        $('#div_goods_search_result').on('click', 'a.demo', function () {
            $('#div_goods_search_result').load($(this).attr('href'));
            return false;
        });

        //选择商品
        $('#div_goods_search_result').on('click', '[nctype="btn_add_groupbuy_goods"]', function () {
            var goods_commonid = $(this).attr('data-goods-commonid');
            $.get('<?php echo urlShop('store_groupbuy', 'groupbuy_goods_info');?>', {goods_commonid: goods_commonid}, function (data) {
                if (data.result) {
                    Item.goods = data.data;
                    $('[nctype="groupbuy_goods_info"]').show();
                    $('#div_search_goods').hide();
                } else {
                    showError(data.message);
                }
            }, 'json');
        });

        //图片上传
        $('[nctype="btn_upload_image"]').fileupload({
            dataType: 'json',
            url: "<?php echo urlShop('store_groupbuy', 'image_upload');?>",
            add: function (e, data) {
                $parent = $(this).parents('dd');
                $input = $parent.find('[nctype="groupbuy_image"]');
                $img = $parent.find('[nctype="img_groupbuy_image"]');
                data.formData = {old_groupbuy_image: $input.val()};
                $img.attr('src', "<?php echo SHOP_TEMPLATES_URL . '/images/loading.gif';?>");
                data.submit();
            },
            done: function (e, data) {
                var result = data.result;
                $parent = $(this).parents('dd');
                $input = $parent.find('[nctype="groupbuy_image"]');
                $img = $parent.find('[nctype="img_groupbuy_image"]');
                if (result.result) {
                    $img.prev('i').hide();
                    $img.attr('src', result.file_url);
                    $img.show();
                    $input.val(result.file_name);
                } else {
                    showError(data.message);
                }
            }
        });

        jQuery.validator.methods.greaterThanDate = function (value, element, param) {
            var date1 = new Date(Date.parse(param.replace(/-/g, "/")));
            var date2 = new Date(Date.parse(value.replace(/-/g, "/")));
            return date1 < date2;
        };

        jQuery.validator.methods.lessThanDate = function (value, element, param) {
            var date1 = new Date(Date.parse(param.replace(/-/g, "/")));
            var date2 = new Date(Date.parse(value.replace(/-/g, "/")));
            return date1 > date2;
        };

        jQuery.validator.methods.greaterThanStartDate = function (value, element) {
            var start_date = $("#start_time").val();
            var date1 = new Date(Date.parse(start_date.replace(/-/g, "/")));
            var date2 = new Date(Date.parse(value.replace(/-/g, "/")));
            return date1 < date2;
        };

//        jQuery.validator.methods.lessThanGoodsPrice = function (value, element) {
//            var goods_price = $("#input_groupbuy_goods_price").val();
//            return Number(value) < Number(goods_price);
//        };

        jQuery.validator.methods.checkGroupbuyGoods = function (value, element) {
            var start_time = $("#start_time").val();
            var result = true;
            $.ajax({
                type: "GET",
                url: '<?php echo urlShop('store_groupbuy', 'check_groupbuy_goods');?>',
                async: false,
                data: {start_time: start_time, goods_id: value},
                dataType: 'json',
                success: function (data) {
                    if (!data.result) {
                        result = false;
                    }
                }
            });
            return result;
        };

        //页面输入内容验证
        $("#add_form").validate({
            errorPlacement: function (error, element) {
                var error_td = element.parent('dd').children('span');
                error_td.append(error);
            },
            onfocusout: false,
            submitHandler: function (form) {
                ajaxpost('add_form', '', '', 'onerror');
            },
            rules: {
                groupbuy_name: {
                    required: true
                },
                start_time: {
                    required: true,
                    greaterThanDate: '<?php echo date('Y-m-d H:i', $output['groupbuy_start_time']);?>'
                },
                end_time: {
                    required: true,
                    <?php if (!$output['isOwnShop']) { ?>
                    lessThanDate: '<?php echo date('Y-m-d H:i', $output['current_groupbuy_quota']['end_time']);?>',
                    <?php } ?>
                    greaterThanStartDate: true
                },
                /*groupbuy_goods_id: {
                    required: true,
                    checkGroupbuyGoods: true
                },
                groupbuy_price: {
                    required: true,
                    number: true,
                    lessThanGoodsPrice: true,
                    min: 0.01,
                    max: 1000000
                },
                virtual_quantity: {
                    required: true,
                    digits: true
                },*/
                upper_limit: {
                    required: true,
                    digits: true
                },
                /*groupbuy_image: {
                    required: true
                }*/
            },
            messages: {
                groupbuy_name: {
                    required: '<i class="icon-exclamation-sign"></i><?php echo $lang['group_name_error'];?>'
                },
                start_time: {
                    required: '<i class="icon-exclamation-sign"></i>抢购开始时间不能为空',
                    greaterThanDate: '<i class="icon-exclamation-sign"></i><?php echo sprintf('抢购开始时间必须大于{0}', date('Y-m-d H:i', $output['current_groupbuy_quota']['start_time']));?>'
                },
                end_time: {
                    required: '<i class="icon-exclamation-sign"></i>抢购结束时间不能为空',
                    <?php if (!$output['isOwnShop']) { ?>
                    lessThanDate: '<i class="icon-exclamation-sign"></i><?php echo sprintf('抢购结束时间必须小于{0}', date('Y-m-d H:i', $output['current_groupbuy_quota']['end_time']));?>',
                    <?php } ?>
                    greaterThanStartDate: '<i class="icon-exclamation-sign"></i>结束时间必须大于开始时间'
                },
                groupbuy_goods_id: {
                    required: '<i class="icon-exclamation-sign"></i><?php echo $lang['group_goods_error'];?>',
                    checkGroupbuyGoods: '该商品已经参加了同时段的活动'
                },
                groupbuy_price: {
                    required: '<i class="icon-exclamation-sign"></i><?php echo $lang['groupbuy_price_error'];?>',
                    number: '<i class="icon-exclamation-sign"></i><?php echo $lang['groupbuy_price_error'];?>',
                    lessThanGoodsPrice: '<i class="icon-exclamation-sign"></i>抢购价格必须小于商品价格',
                    min: '<i class="icon-exclamation-sign"></i><?php echo $lang['groupbuy_price_error'];?>',
                    max: '<i class="icon-exclamation-sign"></i><?php echo $lang['groupbuy_price_error'];?>'
                },
                virtual_quantity: {
                    required: '<i class="icon-exclamation-sign"></i><?php echo $lang['virtual_quantity_error'];?>',
                    digits: '<i class="icon-exclamation-sign"></i><?php echo $lang['virtual_quantity_error'];?>'
                },
                upper_limit: {
                    required: '<i class="icon-exclamation-sign"></i><?php echo $lang['sale_quantity_error'];?>',
                    digits: '<i class="icon-exclamation-sign"></i><?php echo $lang['sale_quantity_error'];?>'
                },
                groupbuy_image: {
                    required: '<i class="icon-exclamation-sign"></i>抢购图片不能为空'
                }
            }
        });

        $('#li_1').click(function () {
            $('#li_1').attr('class', 'active');
            $('#li_2').attr('class', '');
            $('#demo').hide();
        });

        $('#goods_demo').click(function () {
            $('#li_1').attr('class', '');
            $('#li_2').attr('class', 'active');
            $('#demo').show();
        });

        $('.des_demo').click(function () {
            if ($('#des_demo').css('display') == 'none') {
                $('#des_demo').show();
            } else {
                $('#des_demo').hide();
            }
        });

        $('.des_demo').ajaxContent({
            event: 'click', //mouseover
            loaderType: "img",
            loadingMsg: "<?php echo SHOP_TEMPLATES_URL;?>/images/loading.gif",
            target: '#des_demo'
        });
    });

    function insert_editor(file_path) {
        KE.appendHtml('goods_body', '<img src="' + file_path + '">');
    }

    (function (data) {
        var s = '<option value="0"><?php echo $lang['text_no_limit']; ?></option>';
        if (typeof data.children != 'undefined') {
            if (data.children[0]) {
                $.each(data.children[0], function (k, v) {
                    s += '<option value="' + v + '">' + data['name'][v] + '</option>';
                });
            }
        }
        $('#class_id').html(s).change(function () {
            var ss = '<option value="0"><?php echo $lang['text_no_limit']; ?></option>';
            var v = this.value;
            if (parseInt(v) && data.children[v]) {
                $.each(data.children[v], function (kk, vv) {
                    ss += '<option value="' + vv + '">' + data['name'][vv] + '</option>';
                });
            }
            $('#s_class_id').html(ss);
        });
    })($.parseJSON('<?php echo json_encode($output['groupbuy_classes']); ?>'));

</script>


